<?php
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\middleware\api\Auth;
use app\model\CouponUsers;
use app\model\RecordIntegral;
use app\model\Users;
use app\validate\api\CheckId;
use think\facade\Db;

class Coupon extends BaseController
{

    protected $middleware = [
        Auth::class=>['except'=>'index']
    ];

    /**
     * 所有优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($limit=10)
    {
        return $this->success(\app\model\Coupon::order('id','desc')->paginate($limit));
    }

    /**
     * 我的优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myCoupon()
    {
        $user = request()->userid;
        return $this->success(CouponUsers::with('coupon')->where('users_id', $user)->select());
    }

    /**
     * 兌換優惠券
     * @param $id
     * @return \think\response\Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function exchange()
    {

        (new CheckId())->goCheck();
        $user = request()->userid;
        $id=request()->param('id');
        $integrate = Users::where('id', $user)->value('integral_ing');
        $coupon = \app\model\Coupon::find($id);
        if ($coupon->end_time < time()) throw new BaseException(['msg' => '優惠券活動已結束', 'errorCode' => 400]);
        $is_coupon = CouponUsers::where('users_id', $user)->where('coupon_id', $id)->find();
        empty($is_coupon) ? true : throw new BaseException(['msg' => '該優惠券已兌換！']);
        if (empty($integrate) || $integrate < $coupon->integral) {
            throw new BaseException(['msg' => '所需積分不足，兌換失敗！']);
        } else {
            CouponUsers::create(['users_id' => $user, 'coupon_id' => $id]);
            Users::where('id', $user)->dec('integral_ing', $coupon->integral)->update();

            RecordIntegral::record($user,$coupon->integral,RecordIntegral::TYPE_C,RecordIntegral::STATUS_DEC);
            return $this->success();
        }
    }


}
